<script setup lang="ts">
import {message} from "ant-design-vue";
import {
  WxtBiddingConstraintType,
  WxtBiddingDmcType,
  WxtBiddingMethods,
  WxtBiddingSmoothOptions,
  WxtBizCode,
  WxtUtils
} from "~/contentScripts/views/wxt/lib/wxtUtils";

const props = defineProps({
  rows: {
    type: Array,
    default: () => []
  },
  bizCode: {
    type: String as PropType<WxtBizCode>,
    default: ''
  },
  isShow: {
    type: Boolean,
    default: false,
  }
});
const emit = defineEmits(['close']);
const currRows = ref<any[]>(props.rows.map((r: any, index: number) => ({index: index + 1, ...r})));
watch(() => props.isShow, (v) => {
  if (v) {
    currRows.value = props.rows.map((r: any, index: number) => ({index: index + 1, ...r}));
    loadReport();
  } else {
    currRows.value = [];
  }
});
const loadReport = () => {
  currRows.value.forEach((value, index) => {
    WxtUtils.algoGetBudgetSuggestion(props.bizCode, value).then(res => {
      currRows.value[index].budgetSuggestion = res.data.data;
    })
  })
};
loadReport();
const columns = [
  {
    dataIndex: 'index',
    title: '#',
    width: 50,
  },
  {
    dataIndex: 'campaignName',
    title: '计划名称',
    width: 160,
  },
  ...(props.bizCode === WxtBizCode.关键字推广 ? [
    {
      dataIndex: 'dmcType',
      title: '预算类型',
      width: 100,
      align: 'center',
      dataType: 'custom',
      slot: 'dmcType',
    },
    {
      // dataIndex: 'modifyDmcType',
      title: '修改预算类型',
      width: 140,
      dataType: 'custom',
      slot: 'modifyDmcType',
    },
  ] : []),
  {
    dataIndex: 'dayBudget',
    title: '当前预算',
    align: 'center',
    width: 140,
  },
  {
    dataIndex: 'budgetSuggestion',
    title: '建议日预算',
    width: 160,
    dataType: 'custom',
    slot: 'budgetSuggestion',
  },
  {
    dataIndex: 'modifyDayBudget',
    title: '修改预算',
    dataType: 'custom',
    slot: 'modifyDayBudget',
    width: 140,
  },
  ...(props.bizCode === WxtBizCode.关键字推广 ? [
  {
    title: '当前投放方式',
    dataIndex: 'deliveryType',
    dataType: 'custom',
    slot: 'deliveryType',
    width: 120,
  },
  {
    title: '修改投放方式',
    dataIndex: 'modifyDeliveryType',
    dataType: 'custom',
    slot: 'modifyDeliveryType',
    width: 160,
  },
  {
    title: '当前出价方式',
    // dataIndex: 'bidType',
    dataType: 'custom',
    slot: 'bidType',
    align: 'center',
    width: 120,
  },
  {
    title: '修改出价方式',
    dataType: 'custom',
    width: 160,
    slot: 'modifyBidType',
  },
  {
    title: '修改拿量目标',
    dataType: 'custom',
    slot: 'modifyOptimizeTarget',
  }
  ]:[])
];
const radioStyle = reactive({
  display: 'flex',
  height: '30px',
  lineHeight: '30px',
});
const batchDmcType = ref(WxtBiddingDmcType.每日预算);
const batchDayBudget = ref(0);
const batchSetDmcType = () => {
  currRows.value.forEach((r) => {
    r.dmcType = batchDmcType.value;
  })
};
const batchSetDayBudget = () => {
  currRows.value.forEach((r) => {
    r.dayBudget = batchDayBudget.value;
  })
};
const batchSmoothOption = ref(WxtBiddingSmoothOptions.标准投放);
const batchSetSmoothOption = () => {
  currRows.value.forEach((r) => {
    r.smoothOption = batchSmoothOption.value;
  })
};
const batchBidType = ref(WxtBiddingMethods.最大化拿量);
const batchSetBidType = () => {
  currRows.value.forEach((r) => {
    r.bidType = batchBidType.value;
  })
};
const batchOptimizeTarget = ref(WxtBiddingConstraintType.成交金额);
const batchSetOptimizeTarget = () => {
  currRows.value.forEach((r) => {
    r.optimizeTarget = batchOptimizeTarget.value;
  })
};
const batchConstraintType = ref(WxtBiddingConstraintType.直接成交);
const batchConstraintValue = ref(undefined);
const batchSetConstraintValue = () => {
  currRows.value.forEach((r) => {
    r.constraintType = batchConstraintType.value;
    r.constraintValue = batchConstraintValue.value;
  })
};

// 如果只有campaignId 则删除此列
const removeEmptyRows = (updateRows: any[]) => {
  updateRows = updateRows.filter((r: any) => {
    return Object.keys(r).length !== 1;
  });
  return updateRows;
};
const update = () => {
  // console.log('??????update???????', currRows.value);
  const campaignIds: string[] = currRows.value.map((r: any) => r.campaignId);
  // 只修改props.rows 和 currRows.value 的值不对应的字段 获取 campaignBudgetBatchUpdate 的参数 {dmcType:string,campaignId:string,dayBudget:number|null,smoothOption:string|undefined}
  let campaignBudgetBatchUpdateRows: any[] = currRows.value.map((r: any) => {
    const row: any = props.rows.find((row: any) => row.campaignId === r.campaignId);
    return {
      dmcType: r.dmcType,
      campaignId: r.campaignId,
      dayBudget: r.dayBudget,
      smoothOption: r.smoothOption,
    }
  });
  // 剔除掉 除了campaignId其他字段必须至少有一个不为空或者undefined的数据
  campaignBudgetBatchUpdateRows.forEach((r: any) => {
    Object.keys(r).forEach((key: string) => {
      if (key !== 'campaignId' && r[key] === undefined) {
        delete r[key];
      }
    })
  });
  // 如果只有campaignId 则删除此列 并且修复index
  campaignBudgetBatchUpdateRows = removeEmptyRows(campaignBudgetBatchUpdateRows);
  // 只修改props.rows 和 currRows.value 的值不对应的字段 获取 campaignBidBatchUpdate 的参数 {bidType:string,campaignId:string,smoothOption:string|undefined,constraintType:string|undefined,constraintValue:number|undefined}
  let campaignBidBatchUpdateRows: any = currRows.value.map((r: any) => {
    const row: any = props.rows.find((row: any) => row.campaignId === r.campaignId);
    return {
      bidType: r.bidType,
      campaignId: r.campaignId,
      constraintType: r.constraintType,
      constraintValue: r.constraintValue,
    }
  });

  // 剔除掉 除了campaignId其他字段必须至少有一个不为空或者undefined的数据
  campaignBidBatchUpdateRows.forEach((r: any) => {
    Object.keys(r).forEach((key: string) => {
      if (key !== 'campaignId' && r[key] === undefined) {
        delete r[key];
      }
    })
  });
  // 如果只剩下campaignId字段则删除对应列
  campaignBidBatchUpdateRows = removeEmptyRows(campaignBidBatchUpdateRows);
  if (campaignBudgetBatchUpdateRows.length === 0 && campaignBidBatchUpdateRows.length === 0) {
    message.error("表格内数据的预算信息没有修改！！");
    return;
  }
  WxtUtils.campaignBudgetBatchUpdate(campaignBudgetBatchUpdateRows, props.bizCode).then(res => {
    if (res.data.info.ok !== true) {
      message.error(res.data.info.message)
      return;
    }
    message.success("批量修改成功！");
    emit('close');
  });
  if (campaignBidBatchUpdateRows.length === 0) {
    return;
  }
  WxtUtils.campaignBidBatchUpdate(campaignBidBatchUpdateRows, props.bizCode).then(res => {
    if (res.data.info.ok !== true) {
      message.error(res.data.info.message)
      return;
    }
    if (campaignBudgetBatchUpdateRows.length === 0) {
      message.success("批量修改成功！");
      emit('close');
    }
  });
};
</script>

<template>
  <base-table :scroll="{
  y:400,
}" :columns="columns" :data-source="currRows" v-if="props.rows.length>0"
  >
    <template #header>
      <div></div>
    </template>
    <template #budgetSuggestion="row">
      {{
        row.budgetSuggestion ? `${row.budgetSuggestion.budgetLeft || row.budgetSuggestion.budgetLower}-${row.budgetSuggestion.budgetRight || row.budgetSuggestion.budgetUpper}元/天` : '-'
      }}
    </template>
    <template #dmcType="row">
      <span v-if="rows.find((r)=>r.campaignId==row.campaignId).dmcType==WxtBiddingDmcType.每日预算">每日预算</span>
      <span v-else-if="rows.find((r)=>r.campaignId==row.campaignId).dmcType==WxtBiddingDmcType.不限预算">不限预算</span>
    </template>
    <template #modifyDmcType="row">
      <a-radio-group style="width: 100px;" :value="row.dmcType"
                     @change="(e)=>currRows.find((r)=>r.campaignId==row.campaignId).dmcType=e.target.value"
      >
        <a-radio :style="radioStyle" :value="WxtBiddingDmcType.每日预算">每日预算</a-radio>
        <a-radio :style="radioStyle" :value="WxtBiddingDmcType.不限预算">不限预算</a-radio>
      </a-radio-group>
    </template>
    <template #modifyDayBudget="row">
      <a-input-number v-if="row.dmcType==WxtBiddingDmcType.每日预算" size="small" :value="row.dayBudget"
                      @change="(e)=>currRows.find((r)=>r.index==row.index).dayBudget=e"
      >
        <template #addonAfter>元</template>
      </a-input-number>
      <span v-else>不限预算</span>
    </template>
    <template #deliveryType="row">
      <span v-if="currRows.find((r)=>r.index==row.index).dmcType===WxtBiddingDmcType.每日预算">标准投放</span>
      <span v-else-if="currRows.find((r)=>r.index==row.index).bidType==WxtBiddingMethods.手动出价"
      > {{
          currRows.find((r) => r.index == row.index).smoothOption === WxtBiddingSmoothOptions.标准投放 ? '标准投放' : '智能均匀投放'
        }} </span>
      <span v-else> - </span>
    </template>
    <template #modifyDeliveryType="row">
      <a-radio-group v-if="row.bidType==WxtBiddingMethods.手动出价"
                     @change="(e)=>currRows.find((r)=>r.index==row.index).smoothOption=e.target.value"
                     :value="row.smoothOption"
      >
        <a-radio :style="radioStyle" :value="WxtBiddingSmoothOptions.标准投放">标准投放</a-radio>
        <a-radio :style="radioStyle" :value="WxtBiddingSmoothOptions.智能均匀投放">智能均匀投放</a-radio>
      </a-radio-group>
      <div v-else> -</div>
    </template>
    <template #bidType="row">
      <span v-if="row.bidType===WxtBiddingMethods.手动出价">手动出价</span>
      <span v-if="row.bidType===WxtBiddingMethods.最大化拿量">最大化拿量</span>
      <span v-if="row.bidType===WxtBiddingMethods.控成本投放">控成本投放</span>
      <span v-if="row.bidType===WxtBiddingMethods.控投产比投放">控投产比投放</span>
    </template>
    <template #modifyBidType="row">
      <a-radio-group :value="row.bidType"
                     @change="(e)=>currRows.find((r)=>r.index==row.index).bidType=e.target.value"
                     :disabled="row.dmcType!==WxtBiddingDmcType.每日预算 || row.bidType===WxtBiddingMethods.手动出价"
      >
        <a-radio :style="radioStyle" :value="WxtBiddingMethods.最大化拿量">最大化拿量</a-radio>
        <a-radio :style="radioStyle" :value="WxtBiddingMethods.控成本投放">控成本投放</a-radio>
        <a-radio :style="radioStyle" :value="WxtBiddingMethods.控投产比投放">控投产比投放</a-radio>
      </a-radio-group>
    </template>
    <template #modifyOptimizeTarget="row">
      <div v-if="row.bidType===WxtBiddingMethods.最大化拿量">
        <a-radio-group :value="row.optimizeTarget"
                       @change="(e)=>currRows.find((r)=>r.index==row.index).optimizeTarget=e.target.value"
        >
          <a-radio :value="WxtBiddingConstraintType.成交金额">成交金额</a-radio>
          <a-radio :value="WxtBiddingConstraintType.收藏加购">收藏加购</a-radio>
          <a-radio :value="WxtBiddingConstraintType.宝贝点击">宝贝点击</a-radio>
        </a-radio-group>
      </div>
      <div v-else-if="row.bidType === WxtBiddingMethods.控成本投放">
        <a-tooltip title="直接成交/收藏加购下限为5元，宝贝点击下限为0.1元">
          <a-input-number placeholder="请输入" :value="row.constraintValue"
                          :min="row.constraintType==WxtBiddingConstraintType.宝贝点击?0.1:5" step="0.1"
                          size="small"
                          @change="(e)=>currRows.find((r)=>r.index==row.index).constraintValue=e"
          >
            <template #addonBefore>
              <a-select :value="row.constraintType"
                        @change="(e)=>currRows.find((r)=>r.index==row.index).constraintType=e"
                        size="small"
              >
                <a-select-option :value="WxtBiddingConstraintType.直接成交">直接成交</a-select-option>
                <a-select-option :value="WxtBiddingConstraintType.收藏加购">收藏加购</a-select-option>
                <a-select-option :value="WxtBiddingConstraintType.宝贝点击">宝贝点击</a-select-option>
              </a-select>
            </template>
            <template #addonAfter>元</template>
          </a-input-number>
        </a-tooltip>
      </div>
      <div v-else-if="row.bidType === WxtBiddingMethods.控投产比投放">
        <a-tooltip title="投入产出比下限为0.1元">
          <a-input-number placeholder="请输入" :value="row.constraintValue"
                          :min="0.1" step="0.1"
                          size="small"
                          @change="(e)=>currRows.find((r)=>r.index==row.index).constraintValue=e"
          >
            <template #addonAfter>元</template>
          </a-input-number>
        </a-tooltip>
      </div>
      <div v-else>
        -
      </div>
    </template>
  </base-table>
  <a-divider/>
  <a-row type="flex">
    <a-col flex="1">
      <a-form-item label="批量设置预算类型" v-if="bizCode==WxtBizCode.关键字推广">
        <a-space>
          <a-radio-group v-model:value="batchDmcType">
            <a-radio :value="WxtBiddingDmcType.每日预算">每日预算</a-radio>
            <a-radio :value="WxtBiddingDmcType.不限预算">不限预算</a-radio>
          </a-radio-group>
          <a-button type="primary" @click="batchSetDmcType" size="small">应用</a-button>
        </a-space>
      </a-form-item>
      <a-form-item label="批量修改预算">
        <a-space>
          <a-input-number v-model:value="batchDayBudget" size="small"
                          :disabled="batchDmcType===WxtBiddingDmcType.不限预算"
          >
            <template #addonAfter>元</template>
          </a-input-number>
          <a-button type="primary" @click="batchSetDayBudget" :disabled="batchDmcType===WxtBiddingDmcType.不限预算"
                    size="small"
          >应用
          </a-button>
        </a-space>
      </a-form-item>
      <a-form-item label="批量修改投放方式" v-if="bizCode==WxtBizCode.关键字推广">
        <a-space>
          <a-radio-group v-model:value="batchSmoothOption">
            <a-radio :value="WxtBiddingSmoothOptions.标准投放">标准投放</a-radio>
            <a-radio :value="WxtBiddingSmoothOptions.智能均匀投放">智能均匀投放</a-radio>
          </a-radio-group>
          <a-button type="primary" @click="batchSetSmoothOption" size="small">应用</a-button>
        </a-space>
      </a-form-item>
    </a-col>
    <a-col flex="1" v-if="bizCode==WxtBizCode.关键字推广">
      <a-form-item label="批量修改出价方式">
        <a-space>
          <a-radio-group v-model:value="batchBidType" :disabled="batchDmcType===WxtBiddingDmcType.不限预算">
            <a-radio :value="WxtBiddingMethods.最大化拿量">最大化拿量</a-radio>
            <a-radio :value="WxtBiddingMethods.控成本投放">控成本投放</a-radio>
            <a-radio :value="WxtBiddingMethods.控投产比投放">控投产比投放</a-radio>
          </a-radio-group>
          <a-button type="primary" @click="batchSetBidType" :disabled="batchDmcType===WxtBiddingDmcType.不限预算"
                    size="small"
          >应用
          </a-button>
        </a-space>
      </a-form-item>

      <a-form-item label="批量修改拿量目标" v-if="batchBidType===WxtBiddingMethods.最大化拿量">
        <a-space>
          <a-radio-group v-model:value="batchOptimizeTarget" :disabled="batchDmcType===WxtBiddingDmcType.不限预算">
            <a-radio :value="WxtBiddingConstraintType.成交金额">成交金额</a-radio>
            <a-radio :value="WxtBiddingConstraintType.收藏加购">收藏加购</a-radio>
            <a-radio :value="WxtBiddingConstraintType.宝贝点击">宝贝点击</a-radio>
          </a-radio-group>
          <a-button type="primary" @click="batchSetOptimizeTarget"
                    :disabled="batchDmcType===WxtBiddingDmcType.不限预算"
                    size="small"
          >应用
          </a-button>
        </a-space>
      </a-form-item>
      <a-form-item label="批量修改拿量目标" v-if="batchBidType===WxtBiddingMethods.控成本投放">
        <a-space>
          <a-input-number placeholder="请输入" v-model:value="batchConstraintValue"
                          :min="batchConstraintType==WxtBiddingConstraintType.宝贝点击?0.1:5" step="0.1"
                          size="small"
          >
            <template #addonBefore>
              <a-select :value="batchConstraintType"
                        @change="(e)=>batchConstraintType=e"
                        size="small"
              >
                <a-select-option :value="WxtBiddingConstraintType.直接成交">直接成交</a-select-option>
                <a-select-option :value="WxtBiddingConstraintType.收藏加购">收藏加购</a-select-option>
                <a-select-option :value="WxtBiddingConstraintType.宝贝点击">宝贝点击</a-select-option>
              </a-select>
            </template>
            <template #addonAfter>元</template>
          </a-input-number>
          <a-button type="primary" @click="batchSetConstraintValue" size="small">应用</a-button>
        </a-space>
      </a-form-item>
      <a-form-item label="批量修改拿量目标" v-if="batchBidType===WxtBiddingMethods.控投产比投放">
        <a-space>
          <a-input-number placeholder="请输入" v-model:value="batchConstraintValue"
                          :min="0.1" step="0.1"
                          size="small"
          >
            <template #addonAfter>元</template>
          </a-input-number>
          <a-button type="primary" @click="batchSetConstraintValue" size="small">应用</a-button>
        </a-space>
      </a-form-item>
    </a-col>
  </a-row>
  <a-divider/>
  <a-row type="flex" style="text-align: right;">
    <a-col flex="1"/>
    <a-col>
      <a-space>
        <a-button type="default" @click="emit('close')">取消</a-button>
        <a-button type="primary" @click="update">确定</a-button>
      </a-space>
    </a-col>
    <!--    <a-col flex="1"/>-->
  </a-row>
</template>

<style scoped>

</style>
